package com.linln.admin.activityticket;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.linln.common.constant.HeadImgConst;
import com.linln.common.enums.StatusEnum;
import com.linln.common.utils.DateUtil;
import com.linln.common.vo.JsonResult;
import com.linln.common.vo.PageResult;
import com.linln.modules.activityticket.domain.ActivityTicket;
import com.linln.modules.activityticket.service.ActivityTicketService;
import com.linln.modules.integralmall.domain.IntegralMallService;
import com.linln.modules.integralmall.service.IntegralMallServiceService;
import com.linln.modules.system.domain.User;
import com.linln.modules.system.repository.UserRepository;
import com.linln.modules.system.service.UserService;
import com.sargeraswang.util.ExcelUtil.ExcelLogs;
import com.sargeraswang.util.ExcelUtil.ExcelUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @author : pengliang
 * @version V1.0
 * @Project: timo
 * @Package com.linln.admin.activityticket
 * @Descriptio /**
 * @Project: timo
 * @Package com.linln.admin.activityticket
 * @Description: TODO
 * @date Date : 2020年12月21日 10:43
 */
@Controller
@RequestMapping("activityTicket")
public class ActivityTicketController {

    @Autowired
    private ActivityTicketService activityTicketService;

    @Autowired
    private IntegralMallServiceService integralMallService;

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/index")
    public String index() {
        return "/activityTicket/index";
    }


    @GetMapping()
    @ResponseBody
    public Map<String, Object> getPageResult(@RequestParam(required = false, defaultValue = "0") Integer page, @RequestParam(required = false, defaultValue = "10") Integer limit, @RequestParam(defaultValue = "") String activityTicketName) {
        return activityTicketService.getActivityTicket(page, limit, activityTicketName);
    }

    @GetMapping("/integralActivityTicket")
    @ResponseBody
    public PageResult getIntegralActivityTicket() {
        List<ActivityTicket> list = activityTicketService.list(new QueryWrapper<ActivityTicket>().eq("aat_id", "3"));
        return new PageResult(list);
    }

    @PostMapping()
    @ResponseBody
    public JsonResult addPageResult(ActivityTicket activityTicket, String atActivityDate, String atValidDate,String daoluData) throws Exception {
        //赠送批量导入
        if(StringUtils.isNotBlank(daoluData)){
            List<User> userList = new ArrayList<>();
            List<ActivityTicket> activityTicketList = new ArrayList<>();
            Map<String,ActivityTicket> data = new HashMap<>();
            if(StringUtils.isNotBlank(daoluData)){
                List<Map> mapList  = JSONObject.parseArray(daoluData,  Map.class);
                for(Map map : mapList){
                    String status = map.get("status").toString();
                    if("1".equals(status)){
                        String phone = map.get("phone").toString();
                        String nickname = map.get("name").toString();
                        String integral = map.get("integral").toString();
                        String validPeriod = map.get("validPeriod").toString();
                        Set<String> keys = data.keySet();
                        if(keys.contains(validPeriod)){
                            ActivityTicket activityTicketMap = data.get(validPeriod);
                            String oldphone = activityTicketMap.getAtUserPhones();
                            activityTicketMap.setAtUserPhones(oldphone+","+phone);
                        }else {
                            ActivityTicket activityTicketCopy = (ActivityTicket) activityTicket.clone();
                            activityTicketCopy.setAtUserPhones(phone);
                            setDate(activityTicketCopy, atActivityDate, validPeriod);
                            data.put(validPeriod,activityTicketCopy);
                        }
                        User user = null;
                        user = userRepository.findByPhone(phone);
                        if(user == null){
                            user = new User();
                            user.setPhone(phone);
                            user.setNickname(nickname);
                            user.setStatus(StatusEnum.OK.getCode());
                            user.setCreateDate(new Date());
                            user.setHeadImg(HeadImgConst.DEFAULTHEADIMG);
                            user.setPointsLeft(Integer.valueOf(StringUtils.isBlank(integral)?"0":integral));
                        }else {
                            user.setPointsLeft((user.getPointsLeft()==null?0:user.getPointsLeft())+Integer.valueOf(integral));
                        }
                        userList.add(user);
                    }
                }
            }
            Set<String> keys = data.keySet();
            for(String key :keys){
                ActivityTicket a = data.get(key);
                String[] phones = a.getAtUserPhones().split(",");
                a.setAtCount(phones.length);
                activityTicketList.add(a);
            }
            try {
                activityTicketService.batchAddActivityTicketService(activityTicketList,userList);
            }catch (Exception e){
                return JsonResult.error();
            }
            return JsonResult.ok();
        }else {
            setDate(activityTicket, atActivityDate, atValidDate);
            if(!Strings.isBlank(activityTicket.getAtUserPhones())){
                //将中文逗号转换为英文的逗号
                activityTicket.setAtUserPhones(activityTicket.getAtUserPhones().replace("，",","));
            }
            return activityTicketService.addActivityTicketService(activityTicket) ? JsonResult.ok() : JsonResult.error();
        }
    }

    @PutMapping()
    @ResponseBody
    public JsonResult updatePageResult(ActivityTicket activityTicket, String atActivityDate, String atValidDate) {
        setDate(activityTicket, atActivityDate, atValidDate);
        return activityTicketService.updateActivityTicketService(activityTicket) ? JsonResult.ok() : JsonResult.error();
    }

    private void setDate(ActivityTicket activityTicket, String atActivityDate, String atValidDate) {
        if (!Strings.isBlank(atActivityDate)) {
            String date[] = atActivityDate.split(" - ");
            activityTicket.setAtActivityStartDate(date[0]);
            activityTicket.setAtActivityEndDate(date[1]);
        }
        if (!Strings.isBlank(atValidDate)) {
            String date[] = atValidDate.split(" - ");
            activityTicket.setAtValidStartDate(date[0]);
            activityTicket.setAtValidEndDate(date[1]);
        }
    }

    @DeleteMapping("/{atId}")
    @ResponseBody
    public JsonResult deletePageResult(@PathVariable("atId") String atId) {
        if(integralMallService.activityServiceIsItAssociatedByIntegralMall(atId)){
            return JsonResult.error("已被商城服务关联，不能删除");
        }
        return activityTicketService.delActivityTicketService(atId) ? JsonResult.ok() : JsonResult.error();
    }
    @PostMapping("upload")
    @ResponseBody
    public JsonResult upload(MultipartFile file) throws Exception {

        ExcelLogs logs =new ExcelLogs();
        Collection<Map> importExcel = ExcelUtil.importExcel(Map.class, file.getInputStream(), "yyyy/MM/dd HH:mm:ss", logs , 0);

        List<Map<String,Object>> dataList = new ArrayList<>();

        for(Map m : importExcel){
            Map<String,Object> map = new JSONObject();
            String name = (String) m.get("姓名");
            String phone = (String) m.get("电话号码");
            String integral = (String) m.get("积分");
            String validPeriod = (String) m.get("有效期");
            String regular = "^1(3[0-9]|4[5,7]|5[0,1,2,3,5,6,7,8,9]|6[2,5,6,7]|7[0,1,7,8]|8[0-9]|9[1,8,9])\\d{8}$";
            String status = "1";
            String msg = "";
            String[] dates = validPeriod.split("/");
            boolean dateFlag = false;
            boolean phoneFlag = false;
            boolean integralFlag = false;

            //验证日期
            if(dates.length==2){
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    format.setLenient(false);
                    Date state = format.parse(dates[0]);
                    Date end =  format.parse(dates[1]);
                    if(state.getTime()>=end.getTime()){
                        dateFlag = true;
                        msg = "有效期错误";
                    }else {
                        validPeriod = validPeriod.replace("/"," - ");
                    }
                }catch (Exception e){
                    dateFlag = true;
                    msg = "有效期错误";
                }

            }else {
                dateFlag = true;
                msg = "有效期错误";
            }
            //验证手机号
            if(!phone.matches(regular)){
                phoneFlag = true;
                if(StringUtils.isNotBlank(msg)){
                    msg+="，手机号码格式不正确";
                }else {
                    msg="手机号码格式不正确";
                }
            }
            //验证积分
            Pattern pattern = Pattern.compile("[0-9]*");
            if(!pattern.matcher(integral).matches()){
                integralFlag = true;
                if(StringUtils.isNotBlank(msg)){
                    msg+="，积分格式不正确";
                }else {
                    msg="积分格式不正确";
                }
            }
            if(phoneFlag||dateFlag||integralFlag){
                status = "0";
            }
            map.put("name",name);
            map.put("phone",phone);
            map.put("integral",StringUtils.isBlank(integral)?"0":integral);
            map.put("validPeriod",validPeriod);
            map.put("status",status);
            map.put("msg",msg);
            dataList.add(map);
        }
        return JsonResult.ok().put("data", dataList);
    }

    @GetMapping("/download")
    public void downloadAffix(HttpServletResponse response) throws UnsupportedEncodingException {
        String path = ActivityTicketController.class.getClassLoader().getResource("static/excel/客户信息导入表模板.xlsx").getFile();


        path = java.net.URLDecoder.decode(path, "utf-8");
        System.out.println(path);
        File file = new File(path);
        response.setContentType("application/force-download");// 设置强制下载不打开
        response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(),"UTF-8"));
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" +  URLEncoder.encode(file.getName(),"UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream outputStream = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    outputStream.write(buffer, 0, i);
                    i = bis.read(buffer);
                }

//                return JsonResult.ok("下载成功");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
//        return JsonResult.error("下载失败");
    }
}
